import requests
import json
import time
import math

# 读取视频信息
with open("video_keys.json", "r", encoding="utf-8") as f:
    video_data = json.load(f)
with open ("Authorization.json", "r", encoding="utf-8") as f:
    Authorization = json.load(f)
    Token = Authorization['token']

url = "http://69.231.135.101/pgktstudent/messageJW/send"
headers = {
    "Accept": "application/json, text/plain, */*",
    "Content-Type": "application/json",
    "Authorization": Token,
}

REPORT_INTERVAL = 120  # 每两分钟上报一次，单位：秒
cycle_count=0

while 1:
    for course_name, videos in video_data.items():
        for video in videos:
            key = video.get("key")
            video_id = video.get("version_id")
            total_seconds = video.get("playPosition")
            version_name = video.get('version_name')
            if not key or not video_id or not total_seconds:
                print(f"课程《{course_name}》视频信息不全，跳过。")
                continue

            print(f"正在模拟观看《{course_name}》-《{version_name}》，总时长{total_seconds}s")
            steps = max(1, math.ceil(total_seconds / REPORT_INTERVAL))
            for i in range(steps + 1):
                if i == 0:
                    cur_seconds = 0
                    status = "waiting"
                elif i < steps:
                    cur_seconds = min(REPORT_INTERVAL * i, total_seconds)
                    status = "playing"
                else:
                    cur_seconds = total_seconds
                    status = "ended"
                play_ratio = min(cur_seconds / total_seconds, 1)
                data = {
                    "key": key,
                    "id": video_id,
                    "playPosition": round(cur_seconds, 3),
                    "playRatio": round(play_ratio, 6),
                    "playStatus": status
                }
                resp = requests.post(url, headers=headers, json=data, verify=False)
                if resp.status_code != 200:
                    print(f"上报进度{cur_seconds:.2f}s, 状态{status}, 服务器返回: {resp.text}")
                if status != "ended":
                    print("等待120秒...")
                    time.sleep(120)  # 每一步真实等待120秒
    cycle_count=cycle_count+1

    print("全部模拟观看已完成。"+str(cycle_count))